package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Ebook;
import com.jiawa.wiki.req.EbookQueryReq;
import com.jiawa.wiki.req.EbookSaveReq;
import com.jiawa.wiki.resp.EbookQueryResp;
import com.jiawa.wiki.domain.EbookExample;
import com.jiawa.wiki.mapper.EbookMapper;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 荀彧 2021/5/17
 * 电子书 service
 */
@Service
@Slf4j
public class EbookService {

    @Resource
    private EbookMapper mapper;

    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询ebooks
     * @param req
     * @return
     */
    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if (!ObjectUtils.isEmpty(req.getCategory2Id())) {
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo( req.getId());
        }
        // 分页
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook> ebooks = mapper.selectByExample(ebookExample);
        PageInfo<Ebook> info = new PageInfo<>(ebooks);
        log.info("总条数:{}",info.getTotal());
        log.info("总页数:{}",info.getPageNum());
        PageResp<EbookQueryResp> resp = new PageResp<>();
        resp.setTotal(info.getTotal());
        resp.setList(CopyUtil.copyList(ebooks, EbookQueryResp.class));
        return resp;
    }

    public void save(EbookSaveReq saveReq) {
        Ebook ebook = CopyUtil.copy(saveReq,Ebook.class);
        if (ObjectUtils.isEmpty(saveReq.getId())) {
            ebook.setId(snowFlake.nextId());
            mapper.insertSelective(ebook);
        }else {
            mapper.updateByPrimaryKey(ebook);
        }
    }

    /**
     * 删除操作
     * @param id
     */
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }
}

